import { CustomDict } from "../components/custom_views/custom_dict";
import { Dict } from "../components/custom_views/dict";
import { BackendApi } from "./backend_api";
import {CustomDate} from "../components/custom_views/custom_date"
import { TencentImApi } from "./tencent_im_api";

/**
 * 转店相关api PostSellApi
 * list : 查询转店列表， 快速找铺 页面需要调用
 * listOfHighQuality: 首页的查询优质店铺列表 
 * add : 发布转店接口  
 * update: 更新转店的接口
 * getDraft: 获得暂存在本地的转店信息
 * saveDraft:  暂存转店信息到本地
 */
let PostSellApi = {
  /**
   * 快速找铺接口
   * @param {
   * areaCode: '地区编码 非必填'
   * street: '街道名称  非必填'
   * acreageMin: '最低面积   非必填  不填时不限制'
   * acreageMax: '最大面积   非必填  不填时不限制'
   * rentMin: '最低租金   非必填  不填时不限制'
   * rentMax: '最大租金   非必填  不填时不限制'
   * industryId: '行业信息  参考代码 Dict.IndustryTypeEnum '
   * } params 
   * @param {
   * callback 是回调函数，会将该查询结果通过该函数返回
   * 结果参数
   * {
   *  标题：字段进行拼接 「区域：行政区+街道」+「店铺类型」+转让   ，参考产品文档，里面有写 ，店铺类型即行业,
   *  facadePicture: '商铺照片地址，多张用逗号分隔。  不为空  展示第一张',
   *  labelDtoList: [  标签列表
   *    {
   *     labelId: '标签id'
   *     labelName: '标签名称'
   *    }
   *  ],
   *  rent: '月租金'
   * }
   * } callback 
   * @param {
   *  true 或者 false    true 表示 请求时会显示中间的loading 图标，false 不显示
   * } loading 
   */
  list: function(params, callback = function(res){}, loading = true){
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    console.log('###Api接口PostSellApi.list 请求参数', params)
    BackendApi.v05_post_list(params, loading).then(res => {
      console.log('###Api接口PostSellApi.list 响应信息', res)
      callback(res)
    })
  },
  apiList: function(params, loading = true){
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    console.log('###Api接口PostSellApi.list 请求参数', params)
    return BackendApi.v05_post_list(params, loading)
  },
  listOfHighQuality: function(that, callback = function(res){}, loading = true){
    let params = {}
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    params['highQuality'] = Dict.YesEnum.Yes.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    params['pageNum'] = 1
    params['pageSize'] = 100
    console.log('###Api接口PostSellApi.listOfHighQuality 请求参数', params)
    BackendApi.v05_post_list(params, loading).then(res => {
      console.log('###Api接口PostSellApi.listOfHighQuality 响应信息', res)
      if(res.code == 200){
        that.listOfHighQualityData = res.data.records
        if(!res.data.records || res.data.records.length <= 0){
          that.listOfHighQualityNoMore = true
        }else{
          that.listOfHighQualityNoMore = false
        }
      }
      callback(res)
    });
  },
  add: function(params, callback = function(res){}, loading = true){
    console.log('###Api接口PostSellApi.add 请求参数', params)
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    BackendApi.v05_post_add(params, loading).then(res => {
      console.log('###Api接口PostSellApi.add 响应信息', res)
      callback(res)
    })
  },
  update: function(params, callback = function(res){}, loading){
    console.log('###Api接口PostSellApi.add 请求参数', params)
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    BackendApi.v05_post_edit(params, loading).then(res => {
      console.log('###Api接口PostSellApi.update 响应信息', res)
      callback(res)
    })
  },
  getDraft: function(that){
    let postDtoJson = uni.getStorageSync('post_sell_draft')
    if(postDtoJson){
      that.$store.state.myPostOfEditingSell = JSON.parse(postDtoJson)
      return that.$store.state.myPostOfEditingSell
    }else{
      return that.$store.state.myPostOfEditingSell
    }
  },
  saveDraft: function(that, postDto, callback = function(res){}){
    let postDtoJson = JSON.stringify(postDto)
    uni.setStorageSync('post_sell_draft', postDtoJson)
    that.$store.commit('updateMyPostOfEditingSell', postDto)
    callback({code: 200})
  },
  postHis: function(postId, callback = function(res){}, loading = true){
    console.log('###Api接口PostSellApi.postHis 请求参数', postId)
    BackendApi.v05_post_list_his({id: postId}, loading).then(res => {
      console.log('###Api接口PostSellApi.postHis 响应信息', res)
      callback(res)
    });
  },
  postOfInit: function(that, callback = function(res){}, loading = true){
    console.log('###Api接口PostSellApi.postOfInit 请求参数')
    BackendApi.v05_post_list({
      userId: that.$store.state.sessionDto.userDto.userId,
      postMainType: Dict.PostMainTypeEnum.Shop.value,
      postType: Dict.PostMainTypeEnum.Shop.childs.ShopSell.value,
      postStatus: Dict.PostStatusEnum.Init.value,
      pageNum: 1,
      pageSize: 10,
    }, loading).then(res => {
      console.log('###Api接口PostSellApi.postOfInit 响应信息', res)
      callback(res)
    });
  },
}
/**
 * 找店相关api
 * list: 求铺信息 页面需要调用的 查询接口
 * listOfLatest: 首页最新的求租信息的接口
 * add: 发布求铺信息的接口
 * update: 更新发铺信息的接口
 * 
 */
let PostBuyApi = {
  /**
   * 求租信息接口
   * @param {
  * areaCode: '地区编码 非必填'
  * street: '街道名称  非必填'
  * lowerAcreageMin: '最低面积   非必填  不填时不限制'
  * upperAcreageMax: '最大面积   非必填  不填时不限制'
  * lowerRentMin: '最低租金   非必填  不填时不限制'
  * upperRentMax: '最大租金   非必填  不填时不限制'
  * industryId: '行业信息  参考代码 Dict.IndustryTypeEnum '
  * } params 
  * @param {
  * callback 是回调函数，会将该查询结果通过该函数返回
  * 结果参数
  * {
  *  userDto.nickName: '求租人的头像',
  *  标题：字段进行拼接 「区域：行政区+街道」+「店铺类型」+求租   ，参考产品文档，里面有写 店铺类型即行业,
  *  lowerRent: '最低租金',
  *  upperRent: '最高租金  当该值为 >1000000  1百万时 ，代表 租金不限 ',
  *  lowerAcreage: '最小面积',
  *  upperAcreage: '最大面积    当该值  >10000  1万  时，代表 不限 ',
  *  createTimeDesc: '创建时间描述   例如  2天前   ',
  *  createTime: '创建时间',
  * }
  * } callback 
  * @param {
  *  true 或者 false    true 表示 请求时会显示中间的loading 图标，false 不显示
  * } loading 
  */
  list: function(params, callback = function(res){}, loading = true){
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    console.log('###Api接口PostSellApi.list 请求参数', params)
    BackendApi.v05_post_list(params, loading).then(res => {
      console.log('###Api接口 PostBuyApi.list 响应信息', res)
      callback(res)
    })
  },
  apiList: function(params, loading = true){
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    console.log('###Api接口PostBuyApi.apiList 请求参数', params)
    return BackendApi.v05_post_list(params, loading)
  },
  listOfLatest: function(that, params, callback = function(res){}, loading = true){
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    params['postStatus'] = CustomDict.PostStatusEnum.Agree.value
    params['pageNum'] = 1
    params['pageSize'] = 20
    console.log('###Api接口 PostBuyApi.listOfLatest 请求参数', params)
    BackendApi.v05_post_list(params, loading).then(res => {
      console.log('###Api接口 PostBuyApi.listOfLatest 响应信息', res)
      if(res.code == 200){
        that.listOfLatest = res.data.records
        if(!res.data.records || res.data.records.length <= 0){
          that.listOfLatestNoMore = true
        }else{
          that.listOfLatestNoMore = false
        }
      }
      callback(res)
    })
  },
  add: function(params, callback = function(res){}, loading = true){
    console.log('###Api接口 PostBuyApi.add 请求参数', params)
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    BackendApi.v05_post_add(params, loading).then(res => {
      console.log('###Api接口 PostBuyApi.add 响应信息', res)
      callback(res)
    })
  },
  update: function(params, callback = function(res){}, loading = true){
    console.log('###Api接口 PostBuyApi.update 请求参数', params)
    params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    BackendApi.v05_post_edit(params, loading).then(res => {
      console.log('###Api接口 PostBuyApi.update 响应信息', res)
      callback(res)
    })
  }
}
/**
 * 指标相关api
 * updateCollect: 更新记录的收藏状态的接口， value-1 表示收藏；0表示取消收藏
 * updateViewNumber: 更新记录的查询数的接口，需要改造
 */
let MetricRecordApi = {
  updateCollect: function(that, recordId, value, callback = function(res){}, loading = true){
    
    let params = {}
    params['recordType'] = Dict.RecordTypeEnum.Post.value
    params['metricType'] = Dict.MetricTypeEnum.Collect.value
    params['recordId'] = recordId
    params['value'] = value
    params['userId'] = that.$store.state.sessionDto.userDto.userId
    console.log('###Api接口 MetricRecordApi.updateCollect 请求参数', params)
    if(Dict.YesEnum.Yes.value != value && Dict.YesEnum.No.value != value){
      callback({
        code: 400,
        msg: '参数错误',
        data:[]
      })
    }else{
      BackendApi.v05_metricrecord_add(params, loading).then(res => {
        console.log('###Api接口 MetricRecordApi.updateCollect 响应信息', res)
        if(res.code == 200){
          const sessionDto = that.$store.state.sessionDto
          if(params.value == 1){
            sessionDto.metricRecordDtoMap.collectNumber = sessionDto.metricRecordDtoMap.collectNumber + 1
          }else if(params.value == 0){
            sessionDto.metricRecordDtoMap.collectNumber = sessionDto.metricRecordDtoMap.collectNumber - 1
          }
          sessionDto.metricRecordDtoMap.collectNumber = sessionDto.metricRecordDtoMap.collectNumber <= 0 ? 0 :
          sessionDto.metricRecordDtoMap.collectNumber
          that.$store.commit('updateSessionDto', sessionDto)
          callback(res)
        }else{
          callback(res)
        }
      })
    }
  },
  updateViewNumber: function(that, postDto, callback = function(res){}, loading = true){
    let params = {
      id: postDto.id,
      viewNumber: postDto.viewNumber
    }
    console.log('###Api接口 MetricRecordApi.updateViewNumber 请求参数', params)
    BackendApi.v05_post_edit(params, loading).then(res => {
      console.log('###Api接口 MetricRecordApi.updateViewNumber 响应信息', res)
      callback(res)
    })
  },
  /**
   * 清空我的被收藏通知
   * @param {*} taht 
   * @param {*} callback 
   */
  removeCollectNotify: function(that, callback = (res)=>{}, loading = true){
    let params = {
      userId: that.$store.state.sessionDto.userDto.userId,
      notifyType: Dict.MetricTypeEnum.Collect.value
    }
    console.log('###Api接口 MetricRecordApi.removeCollectNotify 请求参数', params)
    BackendApi.v05_usernotify_remove(params, loading).then(res => {
      console.log('###Api接口 MetricRecordApi.removeCollectNotify 响应信息', res)
      if(res.code == 200){
        let sessionDto = that.$store.state.sessionDto
        sessionDto.beenCollectNumber = 0
        that.$store.commit('updateSessionDto', sessionDto)
      }
      callback(res)
    })
  }
}
/**
 * 留言相关api
 * add: 添加留言接口
 * unreadList: 查询未读留言列表
 * allMessageList: 用户的所有消息列表，我的消息页面会调用
 * unreadRemove: 清除未读消息状态，用户进入我的页面后，点击进入我的消息，会消失
 */
let CommentApi = {

  addNew: function(that, postId, targetUserId, content, parentId, recommendRecordId, callback = function(res){}, loading = true){
    let params = {
      recordId: postId,
      targetUserId: targetUserId,
      content: content,
      parentId: parentId ? parentId : 0,
      recordType: Dict.RecordTypeEnum.Post.value,
      
      recommend: recommendRecordId != 0 && recommendRecordId ? 1 : 0,
      recommendRecordId: recommendRecordId != 0 && recommendRecordId ? recommendRecordId : undefined,
      image: '',
      userId: that.$store.state.sessionDto.userDto.userId
    }
    console.log('###Api接口 CommentApi.addNew 请求参数', params)
    BackendApi.v05_comment_add(params, loading).then(res => {
      console.log('###Api接口 CommentApi.addNew 响应信息', res)
      if(res.code == 200){
        let commentUserIds = uni.getStorageSync('commentUserIds')
        if(commentUserIds){
          commentUserIds = commentUserIds + ',' + that.$store.state.sessionDto.userDto.userId
          uni.setStorageSync('commentUserIds', commentUserIds)
        }else{
          uni.setStorageSync('commentUserIds', CustomDate.formatCurrentDate())
        }
      }
      callback(res)
    })
  },
  addImNew: function(that, postId, targetUserId, content, parentId, recommendRecordId, callback = function(res){}, loading = true){
    let params = {
      recordId: postId,
      targetUserId: targetUserId,
      content: content,
      parentId: parentId ? parentId : 0,
      recordType: Dict.RecordTypeEnum.Post.value,
      
      recommend: recommendRecordId != 0 && recommendRecordId ? 1 : 0,
      recommendRecordId: recommendRecordId != 0 && recommendRecordId ? recommendRecordId : undefined,
      image: '',
      userId: that.$store.state.sessionDto.userDto.userId
    }
    console.log('###Api接口 CommentApi.addImNew 请求参数', params)
    BackendApi.v05_comment_imAdd(params, loading).then(res => {
      console.log('###Api接口 CommentApi.addImNew 响应信息', res)
      if(res.code == 200){
        // let commentUserIds = uni.getStorageSync('commentUserIds')
        // if(commentUserIds){
        //   commentUserIds = commentUserIds + ',' + that.$store.state.sessionDto.userDto.userId
        //   uni.setStorageSync('commentUserIds', commentUserIds)
        // }else{
        //   uni.setStorageSync('commentUserIds', CustomDate.formatCurrentDate())
        // }
      }
      callback(res)
    })
  },
  addImNotify: function(that, targetImUserId, callback = function(res){}, loading = true){
    let params = {
      imUserId: targetImUserId,
    }
    console.log('###Api接口 CommentApi.addImNotify 请求参数', params)
    BackendApi.v05_comment_imNotify(params, loading).then(res => {
      console.log('###Api接口 CommentApi.addImNotify 响应信息', res)
      if(res.code == 200){
      }
      callback(res)
    })
  },
  imAddCount: function(that, callback = function(res){}, loading = true){
    let params = {
    }
    console.log('###Api接口 CommentApi.imAddCount 请求参数', params)
    BackendApi.v05_comment_imAddCount(params, loading).then(res => {
      console.log('###Api接口 CommentApi.imAddCount 响应信息', res)
      if(res.code == 200){
      }
      callback(res)
    })
  },
  phoneAddCount: function(that, callback = function(res){}, loading = true){
    let params = {
    }
    console.log('###Api接口 CommentApi.phoneAddCount 请求参数', params)
    BackendApi.v05_track_countOfPhone(params, loading).then(res => {
      console.log('###Api接口 CommentApi.phoneAddCount 响应信息', res)
      if(res.code == 200){
      }
      callback(res)
    })
  },
  // 当日留言次数是否超额
  overLimitCommentNumber: function(targetUserId){
    let commentUserIds = uni.getStorageSync('commentUserIds')
    let ary = commentUserIds ? commentUserIds.split(',') : []
    if(ary.length > 0 && targetUserId){
      let isToday = CustomDate.formatCurrentDate() <= ary[0]
      if(isToday && ary.length >= 2 && ary.every(existUserId => existUserId != targetUserId)){
        return true
      }
    }
    return false

    // if(commentUserIds){
    //   let ary = commentUserIds.split(',')
    //   if(!ary && ary.length <= 5){
    //     // 留言用户少于5人
    //     return false
    //   }else{
    //     let isToday = CustomDate.formatCurrentDate() <= ary[0]
    //     if(isToday && ary.some(existUserId => existUserId != currentUserId)){
    //       return true
    //     }
    //   }
    // }else{
    //   return false
    // }
    
  },
  unreadList: function(that,callback = (res1)=>{}, loading = true){
    console.log('###Api接口 CommentApi.unreadList 请求')
    BackendApi.v05_comment_unread_list({}).then(res => {
      console.log('###Api接口 CommentApi.unreadList 响应信息', res.data)
      callback(res)
    })
  },
  allMessageList: function(params, that,callback = (res1)=>{}, loading = true){
    console.log('###Api接口 CommentApi.allMessageList 请求', params)
    return BackendApi.v05_comment_listMessage(params, loading)
    // BackendApi.v05_comment_listMessage(params).then(res => {
    //   console.log('###Api接口 CommentApi.allMessageList 响应信息', res.data)
    //   callback(res)
    // })
  },
  unreadRemove: function(that,callback = (res1)=>{}, loading = true){
    console.log('###Api接口 CommentApi.unreadRemove 请求')
    BackendApi.v05_comment_unread_remove({}).then(res => {
      console.log('###Api接口 CommentApi.unreadRemove 响应信息', res.data)
      if(res.code == 200){
        let sessionDto = that.$store.state.sessionDto
        sessionDto.unreadCommentNumber = 0
        that.$store.commit('updateSessionDto', sessionDto)
      }
      callback(res)
    })
  }
}
/**
 * 找铺、转铺共有的api（包括找铺、转铺的）
 * listOfInit:查询待审核状态的数据
 * detail: 查询发布信息的详情，详情页面需要调用
 * updateByFinish: 更新发布信息为交易完成状态
 * del: 删除发布信息
 * listOfCollect: 查询我的收藏，包括找铺和转铺的。
 * refreshMyPostList: 查询我的发布信息的接口，并缓存在store中
 */
let PostApi = {
  listOfInit: function(that, callback = function(res){}, loading = true){
    let params = {}
    params['postStatus'] = CustomDict.PostStatusEnum.Init.value
    params['postType'] = Dict.PostMainTypeEnum.Shop.childs.ShopSell.value
    params['pageNum'] = 1
    params['pageSize'] = 50
    console.log('###Api接口 PostApi.listOfInit 请求参数', params)
    BackendApi.v05_post_list(params, loading).then(res =>{
      console.log('###Api接口 PostApi.listOfInit 响应信息', res)
      callback(res)
    })
  },
  detail: function(postId, callback = function(res){}, loading = true){
    console.log('###Api接口 PostApi.detail 请求参数', postId)
    BackendApi.v05_post_detail({id: postId}, loading).then(res =>{
      console.log('###Api接口 PostApi.detail 响应信息', res)
      callback(res)
    })
  },
  updateByFinish: function(postId, callback = (res)=>{}, loading = true){
    console.log('###Api接口 PostApi.updateByFinish 请求参数', postId)
    BackendApi.v05_post_edit({id: postId, 
      postStatus: Dict.PostStatusEnum.Finish.value}, loading).then(res =>{
        console.log('###Api接口 PostApi.updateByFinish 响应信息', res)
      callback(res)
    })
  },
  del: function(postId, callback = function(res){}, loading = true){
    console.log('###Api接口 PostApi.del 请求参数', postId)
    BackendApi.v05_post_my_del({postId: postId}, loading).then(res =>{
      console.log('###Api接口 PostApi.del 响应信息', res)
      callback(res)
    })
  },
  /**
   * 查询我的收藏接口，会返回 转店的和 找店的所有收藏
   * 入参无。
   * 响应参数同，PostSellApi.list
   * @param {} that 
   * @param {*} callback 
   * @param {*} loading 
   */
  listOfCollect: function(that, callback = function(res){}, loading = true){
    console.log('###Api接口 PostApi.listOfCollect 请求参数')
    BackendApi.v05_post_list({
      userId: that.$store.state.sessionDto.userDto.userId,
      metricType: Dict.MetricTypeEnum.Collect.value
    }, loading).then(res =>{
      console.log('###Api接口 PostApi.listOfCollect 响应信息', res)
      callback(res)
    })
  },
  listOfBeenCollect: function(that, loading = true){
    console.log('###Api接口 PostApi.listOfBeenCollect 请求参数')
    return BackendApi.v05_post_list({
      userId: that.$store.state.sessionDto.userDto.userId,
      targetMetricType: Dict.MetricTypeEnum.Collect.value
    }, loading)
  },
  refreshMyPostList: function(that, callback = function(res){}, loading = true){
    let params = {}
    let userId = that.$store.state.sessionDto.userDto.userId
    if(userId){
      params['postMainType'] = Dict.PostMainTypeEnum.Shop.value
      params['pageNum'] = 1
      params['pageSize'] = 100
      params['userId'] = userId
      console.log('###Api接口 PostApi.refreshMyPostList 请求参数', params)
      BackendApi.v05_post_list(params, loading).then(res => {
        console.log('###Api接口 PostApi.refreshMyPostList 响应信息', res)
        if(res.code == 200){
          that.$store.commit('updateMyPostList', res.data.records)
        }
        callback(res)
      })
    }else{
      callback({code: 500, msg: '参数错误'})
    }
    
  },
 
  /**
   * 发帖审核接口
   * @param {} that 
   * @param {*} postId 发帖id
   * @param {*} postStatus 审核状态
   * @param {*} postStatusDesc 状态描述
   * @param {*} postScore 分值
   * @param {*} callback 
   */
  audit: function(that, postId, postStatus, postStatusDesc, postScore, callback = (res)=>{}, loading = true){
    let params = {
      id: postId,
      postStatus: postStatus,
      postStatusDesc: postStatusDesc,
      postScore: postScore
    }
    console.log('###Api接口 PostApi.audit 请求参数', params)
    BackendApi.v05_post_audit(params, loading).then(res =>{
      console.log('###Api接口 PostApi.audit 响应信息', res)
      callback(res)
    })
  },
  addPostNumber: function(that, addNum, postId = undefined){
    let sessionDto = that.$store.state.sessionDto
    sessionDto.postNumber = sessionDto.postNumber + addNum
    that.$store.commit('updateSessionDto', sessionDto)

    let myPostList = that.$store.state.myPostList
    if(postId && addNum == -1 && myPostList && myPostList.length > 0){
      myPostList = myPostList.filter(post => post.id != postId)
      that.$store.commit('updateMyPostList', myPostList)
    }
  },
  addPostBuyNumber: function(that, addNum, postId = undefined){
    let sessionDto = that.$store.state.sessionDto
    sessionDto.postBuyNumber = sessionDto.postBuyNumber + addNum
    that.$store.commit('updateSessionDto', sessionDto)

    let myPostList = that.$store.state.myPostList
    if(postId && addNum == -1 && myPostList && myPostList.length > 0){
      myPostList = myPostList.filter(post => post.id != postId)
      that.$store.commit('updateMyPostList', myPostList)
    }
  }
}
let auditPostId = 0
/**
 * 我的浏览
 * add: 添加我的留言
 * list: 查询我的浏览
 */
let FootprintsApi = {
  add: function(postId, callback = function(res){}, loading = true){
    console.log('###Api接口 FootprintsApi.add 请求参数', postId)
    BackendApi.v05_footprints_add({postId: postId,}, loading).then(res =>{
      console.log('###Api接口 FootprintsApi.add 响应信息', res)
      callback(res)
    })
  },
  /**
   * 我的浏览接口，入参无
   * 响应，同 PostSellApi.list 和PostBuyApi.list
   * @param {} callback 回调函数
   * @param {*} loading 
   */
  list: function(params, loading = true){
    console.log('###Api接口 FootprintsApi.list 请求参数', params)
    return BackendApi.v05_footprints_list(params, loading)
  },
  /**
   * 查询谁浏览了我的发帖信息
   * @param {*} params 
   * @param {*} loading 
   * @returns 
   */
  listOfExposure: function(params, loading = true){
    console.log('###Api接口 FootprintsApi.listOfExposure 请求参数', params)
    return BackendApi.v05_footprints_listofexposure(params, loading)
  }
}
/**
 * 登录相关
 * login: 用户登陆接口。登陆成功返回sessionDto信息，缓存在store中
 * isFirstLogin: 判断是否首次登陆
 * nickNameUpdated: 判断用户昵称是否已经修改过，即昵称是否以Bh开头，以Bh开头即表示是自动生成的昵称。
 */
let LoginApi = {
  /**
   * 登录相关接口
   * @param {} callback 
   */
  login: function(that, callback, loading = true){
    // 从本地缓存中拿登录信息，判断是否已登录
    let userId = uni.getStorageSync('userId')
    if(userId){
      uni.setStorageSync('firstLogin', 0)
      console.log('###Api接口 LoginApi.login 请求参数', userId)
      BackendApi.v05_user_query({
        userId: userId
      }, loading).then(res => {
        console.log('###Api接口 LoginApi.login 响应信息', res)
        if(res.code == 200){
          that.$store.commit('updateSessionDto', res.data)
          uni.setStorageSync('userId', userId)
        }
        callback(res)
      })
    }else{
      uni.setStorageSync('firstLogin', 1)
      uni.login({
        success: function (codeRes){
          console.log('###Api接口 LoginApi.login 请求参数', codeRes)
          BackendApi.v05_login_mp_loginWechatAuto({
            code: codeRes.code
          }, loading).then(res => {
            console.log('###Api接口 LoginApi.login 响应信息', res)
            if(res.code == 200){
              that.$store.commit('updateSessionDto', res.data)
              uni.setStorageSync('userId', res.data.userDto.userId)
            }
            callback(res)
          })
        },
        fail: function (codeErr){
          console.log('小程序wx.login失败', codeErr)
          callback({
            code: 510,
            msg: '无权访问'
          })
        }
      })
    }
  },
  isFirstLogin: function(that){
    console.log('是否第一次登陆', uni.getStorageSync('firstLogin'))
    return uni.getStorageSync('firstLogin') !== 1
  },
  nickNameUpdated: function(that){
    console.log('session信息信息', that.$store.state.sessionDto.userDto)
    return that.$store.state.sessionDto.userDto.nickName.startsWith('Bh')
  }
}
/**
 * 用户相关
 * updateUserRole: 更新用户角色 角色id  
 * getUserRole: 获得用户当前的角色
 * updateNickNameAndAvatarUrl: 更新用户的头像和昵称
 */
let UserApi = {
  updateUserRole: function(roleId){
    uni.setStorageSync('userRoleId', roleId)
    return;
  },
  getUserRole: function(){
    let userRoleId = uni.getStorageSync('userRoleId')
    if(!userRoleId){
      uni.setStorageSync('userRoleId',Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value)
      return Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
    }
    return userRoleId
  },
  /**
   * 更新用户头像和昵称
   * @param {*} that 调用该方法所在vue页面的this指针
   * @param {*} nickName 需要保存的昵称
   * @param {*} avatarUrl 需要保存的头像地址
   * @param {*} callback 回调函数
   */
  updateNickNameAndAvatarUrl(that, nickName, avatarUrl, callback = (res) => {}){
    if(nickName && avatarUrl){
      BackendApi.v05_user_edit({
        userId: uni.getStorageSync('userId'),
        nickName: nickName,
        avatarUrl: avatarUrl
      }).then(res => {
        if(res.code == 200){
          let sessionDto = that.$store.state.sessionDto
          sessionDto.userDto.nickName = nickName
          sessionDto.userDto.avatarUrl = avatarUrl
          that.$store.commit('updateSessionDto', sessionDto)
        }
        callback(res)
      })
    }else{
      callback({code: 500, msg: '参数错误'})
    }
    
  },
  getUserSig(callback = (res) => {}){
    let userId = uni.getStorageSync('userId')
    if (userId) {
      console.log('用户userId不为空，用户已经登录')
      TencentImApi.genUserSig().then(res => {
        console.log('用户获取im的userSig信息', res)
        callback(res)
      })
    } else {
      console.log('用户userId为空，还未登录')
    }
  },
  jsapiOrder(that, params, callback = (res) => {}, loading){
	  console.log('###Api接口 UserApi.jsapiOrder 请求参数', params)
	  BackendApi.wechatPay_jsapiOrder({}, loading).then((res) => {
		  console.log('###Api接口 UserApi.jsapiOrder 响应信息', res)
		  callback(res)
	  })
  },
  jsapiOrderQuery(that, params, callback = (res) => {}, loading){
  	  console.log('###Api接口 UserApi.jsapiOrderQuery 请求参数', params)
  	  BackendApi.wechatPay_jsapiOrderQuery(params, loading).then((res) => {
  		  console.log('###Api接口 UserApi.jsapiOrderQuery 响应信息', res)
  		  callback(res)
  	  })
  },
  jsapiMemberRefund(that, params, callback = (res) => {}, loading){
  	  console.log('###Api接口 UserApi.jsapiMemberRefund 请求参数', params)
  	  BackendApi.wechatPay_jsapiMemberRefund(params, loading).then((res) => {
  		  console.log('###Api接口 UserApi.jsapiMemberRefund 响应信息', res)
  		  callback(res)
  	  })
  },
  memberPayRecord(params, loading){
  	  console.log('###Api接口 UserApi.memberPayRecord 请求参数', params)
	  return BackendApi.wechatPay_memberPayRecord(params, loading)
  	  // BackendApi.wechatPay_memberPayRecord(params, loading).then((res) => {
  		 //  console.log('###Api接口 UserApi.memberPayRecord 响应信息', res)
  		 //  callback(res)
  	  // })
  },
}
/**
 * 公告相关
 * list: 获取系统的公告信息
 */
let NoticeApi = {
  list: function(callback = function(res){}, loading = true){
    console.log('###Api接口 NoticeApi.list 请求参数', {})
    BackendApi.v05_notice_list({}, loading).then(res => {
      console.log('###Api接口 NoticeApi.list 响应信息', res)
      callback(res)
    })
  }
}
/**
 * 我的页面中的api
 * refresh: 我的页面，下啦刷新时调用，
 * getMetricRecordMap:  暂时不用
 * listOfMy: 查询我发布的信息，
 */
let MyApi = {
  refresh: function(that, callback = function(res){}, loading = true){
    // 从本地缓存中拿登录信息，判断是否已登录
    let userId = uni.getStorageSync('userId')
    if(userId){
      console.log('###Api接口MyApi.refresh 请求参数', {})
      BackendApi.v05_user_query({
        userId: userId
      }, loading).then(res => {
        console.log('###Api接口MyApi.refresh 响应信息', res)
        if(res.code == 200){
          that.$store.commit('updateSessionDto', res.data)
          uni.setStorageSync('userId', userId)
        }
        callback(res)
      })
    }else{
      uni.login({
        success: function (codeRes){
          console.log('###Api接口 MyApi.refresh 请求参数', codeRes)
          BackendApi.v05_login_mp_loginWechatAuto({
            code: codeRes.code
          }, loading).then(res => {
            console.log('###Api接口 MyApi.refresh 响应信息', res)
            if(res.code == 200){
              that.$store.commit('updateSessionDto', res.data)
              uni.setStorageSync('userId', res.data.userDto.userId)
            }
            callback(res)
          })
        },
        fail: function (codeErr){
          console.log('小程序wx.login失败', codeErr)
        }
      })
    }
  },
  getMetricRecordMap: function(){
    return {}
  },
  /**
   * 我的发布，包括我发布的找铺信息   和我发布的转铺信息
   * @param {} that 
   * @param {*} callback 
   * @param {*} loading 
   */
  listOfMy: function(that, callback = function(res){}, loading = true){
    if(!that.$store.state.sessionDto.userDto.userId){
      callback({
        code: 500,
        msg: '用户未登录'
      })
    }else{
      if(that.$store.state.myPostList && that.$store.state.myPostList.length >0 ){
        callback({
          code: 200,
          data:{
            records:that.$store.state.myPostList
          }
        })
        return
      }
      let params = {
        userId: that.$store.state.sessionDto.userDto.userId,
        postStatus: Dict.PostStatusEnum.Agree.value,
        pageNum: 1,
        pageSize: 100
      }
      console.log('###Api接口 MyApi.listOfMy 请求参数', params)
      BackendApi.v05_post_list(params, loading).then(res => {
        console.log('###Api接口 MyApi.listOfMy 响应信息', res)
        if(res.code == 200){
          that.$store.commit('updateMyPostList', res.data.records)
        }
        callback(res)
      }, false)
    }
  },
  refreshListOfMy: function(that,){
    that.$store.commit('updateMyPostList', [])
  },
}
/**
 * 交易案例
 * list: 查询交易案例
 */
let PostTransCaseApi = {
  /**
   * 
   * @param {
  * callback 是回调函数，会将该查询结果通过该函数返回
  * 结果参数
  * {
  *  标题：字段进行拼接 「区域：行政区+街道」+「店铺类型」+转让   ，参考产品文档，里面有写 ，店铺类型即行业,
  *  facadePicture: '商铺照片地址，多张用逗号分隔。  不为空  展示第一张',
  *  labelDtoList: [  标签列表
  *    {
  *     labelId: '标签id'
  *     labelName: '标签名称'
  *    }
  *  ],
  *  rent: '月租金'
  * }
   * } callback 
   * @param {*} loading 
   */
  /**
   * 分页查询交易案例
   * 响应参数，
   * {
   *  标题：字段进行拼接 「区域：行政区+街道」+「店铺类型」+转让   ，参考产品文档，里面有写 ，店铺类型即行业,
   *  facadePicture: '商铺照片地址，多张用逗号分隔。  不为空  展示第一张',
   *  labelDtoList: [  标签列表
   *    {
   *     labelId: '标签id'
   *     labelName: '标签名称'
   *    }
   *  ],
   *  rent: '月租金'
   * }
   * @param {*} pageNum 页码
   * @param {*} pageSize 页数
   * @param {*} callback 回调函数
   * @param {*} loading 
   */
  list: function(pageNum, pageSize, callback = function(res){}, loading = true){
    console.log('###Api接口PostTransCaseApi.list 请求参数', {})
    BackendApi.v05_postTransCase_list({pageNum: pageNum, pageSize: pageSize}, loading).then(res => {
      console.log('###Api接口PostTransCaseApi.list 响应信息', res)
      callback(res)
    }, true)
  }
}

let areaStreetListRes = undefined

/**
 * 常量相关接口
 * areaSteetList: 根据城市编码查询，区域和街道信息，目前固定城市 北京。北京编码查看store
 */
let ConstantApi = {
  areaStreetList: function(cityCode, callback = function(res){}, loading = true){
    console.log('###Api接口 ConstantApi.areaStreetList 请求参数', {})
    if(areaStreetListRes){
      console.log('### ConstantApi.areaStreetList 之前请求过，返回缓存中的数据')
      callback(areaStreetListRes)
      return
    }
    BackendApi.v05_const_region_areaStreetList({cityCode: cityCode}, loading).then(res => {
      console.log('###Api接口 ConstantApi.areaStreetList 响应信息', res)
      areaStreetListRes = res
      callback(res)
    })
  }
}
/**
 * 小程序通知功能
 * @param {*} sucCallback 允许通知回调
 * @param {*} failCallback 拒绝通知回调
 */
let CustRequestSubscribeMessage = function(sucCallback, failCallback = (err)=>{}){
  uni.requestSubscribeMessage({
    // 留言通知、帖子被收藏通知、
    tmplIds: ['rde2nNh-bwYaOLC8_VEUJo35zD_G_XRGd8pzrZJK0QA', 'SatyFF0dG2Asi3caTX8tVOT_GtnObUhOSEH945zpuOc', '2css3nULpDDp3NO-UdVbX07VVO3lsvjhxKqRVIDnIoI'],
    success(res) {
      console.log('允许订阅回复提醒消息', res)
      sucCallback()
    },
    fail(err) {
      console.log('允许订阅回复提醒消息返回异常', err)
      failCallback()
    }
  })
}

let TrackApi = {
  trackAdd: function(that, params, callback){
    console.log('###Api接口 TrackApi.trackAdd 请求参数', params)
    BackendApi.v05_track_add(params, false).then(res => {
      console.log('###Api接口 TrackApi.trackAdd 响应信息', res)
      callback(res)
    })
  },
  v05_track_listv2: function(that, params, callback){
    console.log('###Api接口 TrackApi.v05_track_listv2 请求参数', params)
    BackendApi.v05_track_listv2(params, false).then(res => {
      console.log('###Api接口 TrackApi.v05_track_listv2 响应信息', res)
      callback(res)
    })
  },
}


export const Api = {
  PostSellApi,PostBuyApi,
  MetricRecordApi,CommentApi,
  PostApi,FootprintsApi,
  LoginApi,UserApi,
  NoticeApi,MyApi,
  PostTransCaseApi,
  ConstantApi,
  CustRequestSubscribeMessage,
  auditPostId,
  TrackApi
}
